<template>
    <div class="page-main">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
            <div v-if="isLoading && !waterfallColumns[0].length" class="loading-container">
                <van-loading type="spinner" color="#1989fa" />
            </div>
            <div v-else class="waterfall-container" :class="{ 'fade-in': !isLoading }">
                <div class="waterfall-column" v-for="(column, index) in waterfallColumns" :key="index">
                    <div
                        v-for="card in column"
                        :key="card.id"
                        class="card-item"
                        @click="goToDetail(card.id)"
                    >
                        <div class="card-img">
                            <img v-lazy="card.coverImg" alt="文章图片" />
                        </div>
                        <div class="card-content">
                            <h3 class="title">{{ card.title }}</h3>
                            <p class="content">{{ card.content }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </van-pull-refresh>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { getCardInfo } from '../api/index';
import { showToast } from 'vant';

const router = useRouter();

const cardList = ref([]);
const waterfallColumns = ref([[], []]); // 默认两列
const refreshing = ref(false);
const refreshTimer = ref(null);
const isLoading = ref(true);
const cacheKey = 'waterfall_card_cache';
const cacheExpiryKey = 'waterfall_cache_expiry';
const cacheExpiry = 5 * 60 * 1000; // 5分钟缓存过期

// 从缓存加载数据
const loadFromCache = () => {
    try {
        const cachedData = localStorage.getItem(cacheKey);
        const expiry = localStorage.getItem(cacheExpiryKey);
        
        if (cachedData && expiry) {
            if (Date.now() < parseInt(expiry)) {
                // 缓存未过期，使用缓存数据
                cardList.value = JSON.parse(cachedData);
                return true;
            }
        }
    } catch (error) {
        console.error('读取缓存数据失败:', error);
    }
    return false;
};

// 保存数据到缓存
const saveToCache = (data) => {
    try {
        localStorage.setItem(cacheKey, JSON.stringify(data));
        localStorage.setItem(cacheExpiryKey, (Date.now() + cacheExpiry).toString());
    } catch (error) {
        console.error('保存缓存数据失败:', error);
    }
};

// 获取卡片列表数据
const getCardList = async (forceRefresh = false) => {
    // 如果不是强制刷新且已经有数据，则不重新加载
    if (!forceRefresh && cardList.value.length > 0) {
        return;
    }
    
    // 如果不是强制刷新，尝试从缓存加载
    if (!forceRefresh && loadFromCache()) {
        isLoading.value = false;
        return;
    }
    
    isLoading.value = true;
    try {
        const res = await getCardInfo();
        cardList.value = res.data.data;
        // 保存到缓存
        saveToCache(res.data.data);
        // 更新最后刷新时间
        localStorage.setItem('lastRefreshTime', Date.now().toString());
    } catch (error) {
        showToast('获取文章列表失败，请稍后重试');
        console.error(error);
    } finally {
        isLoading.value = false;
    }
};

// 下拉刷新处理函数
const onRefresh = async () => {
    await getCardList(true); // 强制刷新
    refreshing.value = false;
};

// 分配卡片到列中，实现瀑布流效果，并随机排列
const distributeCards = () => {
    if (!cardList.value.length) return;
    
    const columns = [[], []]; // 两列

    // 对 cardList.value 进行随机排序
    const shuffledCards = [...cardList.value].sort(() => Math.random() - 0.5);

    shuffledCards.forEach((card, index) => {
        // 根据索引奇偶性分配到不同列
        const columnIndex = index % 2;
        columns[columnIndex].push(card);
    });

    waterfallColumns.value = columns;
};

// 检查是否需要自动刷新数据
const checkAutoRefresh = () => {
    const lastRefreshTime = localStorage.getItem('lastRefreshTime');
    const now = Date.now();
    
    // 如果没有最后刷新时间或者时间超过10分钟，自动刷新
    if (!lastRefreshTime || (now - parseInt(lastRefreshTime)) > 10 * 60 * 1000) {
        getCardList(true);
    }
};

// 设置定时自动刷新 (每10分钟刷新一次)
const setupAutoRefresh = () => {
    // 先检查一次是否需要刷新
    checkAutoRefresh();
    
    // 设置定时器，每10分钟检查一次是否需要刷新
    refreshTimer.value = setInterval(checkAutoRefresh, 10 * 60 * 1000);
};

watch(cardList, () => {
    distributeCards();
});

const goToDetail = (id) => {
    router.push({
        name: 'ArticleContent',
        params: { id }
    });
};

onMounted(() => {
    getCardList();
    setupAutoRefresh();
});

// 当组件被keep-alive激活时调用
onActivated(() => {
    // 仅检查是否需要刷新，不强制刷新
    checkAutoRefresh();
});

onUnmounted(() => {
    // 清除定时器
    if (refreshTimer.value) {
        clearInterval(refreshTimer.value);
    }
});
</script>

<style lang="scss" scoped>
.page-main {
    background-color: #fff;
    min-height: 100vh;
    padding: 0 10px;

    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
    }
    
    .fade-in {
        animation: fadeIn 0.3s ease-in;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    .waterfall-container {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        
        .waterfall-column {
            flex: 1;
            max-width: calc(50% - 5px); // 两列，减去间隙
            
            &:first-child {
                margin-right: 5px;
            }
            
            &:last-child {
                margin-left: 5px;
            }
        }
        
        .card-item {
            text-align: center;
            border-radius: 8px;
            margin-bottom: 10px;
            background: #f3f0f0;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            display: flex;
            flex-direction: column;
            overflow: hidden;

            .card-img {
                height: auto; // 高度由图片自身决定
                flex-shrink: 0;

                img {
                    width: 100%;
                    height: auto; // 保持图片原始比例
                    object-fit: cover;
                    border-radius: 8px;
                }
            }

            .card-content {
                padding: 2px;
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-between;

                .title {
                    font-size: 13px;
                    font-weight: bold;
                    color: #333;
                    margin: 2px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .content {
                    font-size: 10px;
                    color: #666;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .time {
                    font-size: 12px;
                    color: #999;
                    align-self: flex-end;
                }
            }
        }
    }
}
</style>